package com.um.jdy.common.charge.service.impl;


import cn.hutool.core.date.*;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.charge.entity.po.OrderPlace;
import com.um.jdy.common.charge.enums.OrderEnum;
import com.um.jdy.common.charge.service.OrderPlaceFeeService;
import com.um.jdy.common.charge.service.OrderPlaceTimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import com.um.springboot.starter.orm.service.BaseEntityServiceImpl;
import com.um.jdy.common.charge.service.EboxOrderService;
import com.um.jdy.common.charge.dao.EboxOrderDao;
import com.um.jdy.common.charge.entity.po.EboxOrder;

import java.util.Date;

/**
 * 服务实现类：充电柜订单扩展表
 */
@Service
@Slf4j
public class EboxOrderServiceImpl extends BaseEntityServiceImpl<EboxOrderDao,EboxOrder>  implements EboxOrderService{

    @Autowired
    OrderPlaceFeeService orderPlaceFeeService;

    @Autowired
    OrderPlaceTimeService orderPlaceTimeService;

    @Override
    public Integer getPlaceAmount(OrderPlace orderPlace, EboxOrder eboxOrder) {
        if (!orderPlace.getStatus().equals(YesOrNo.Yes.name())) {//不收占位费
            return 0;
        }

        if (orderPlace.getStatus().equals(YesOrNo.Yes.name())) {
            eboxOrder.setPlaceSeconds(getPlaceSeconds(orderPlace,eboxOrder));
            eboxOrder.setPlaceAmount(getPlaceAmount(orderPlace, eboxOrder.getPlaceSeconds()));
        }

        return eboxOrder.getPlaceAmount();

    }

    @Override
    public int getPlaceSeconds(OrderPlace orderPlace, EboxOrder eboxOrder) {
        Date endTime = eboxOrder.getPlaceEndTime() == null ? new Date() : eboxOrder.getPlaceEndTime();
        long between = DateUtil.between(eboxOrder.getPlaceBeginTime(), endTime, DateUnit.SECOND);
        eboxOrder.setPlaceSeconds((int) Math.max(0, between));
        return eboxOrder.getPlaceSeconds();
    }


    /**
     * 计算占位费用
     * @param orderPlace
     * @param placeSeconds
     * @return
     */
    private int getPlaceAmount(OrderPlace orderPlace,int placeSeconds){
        int placeAmount = 0;
        //如果开启收取占位费
        if (orderPlace.getStatus().equals(YesOrNo.Yes.name())) {

            //前多少分钟免费
            if(placeSeconds <= orderPlace.getFreeDuration() * 60)
                return 0;

            placeSeconds = getHourCeilTime(Math.max(0,placeSeconds));
            placeAmount = Math.min(orderPlace.getPrice() * placeSeconds / 3600, orderPlace.getMaxAmount());
        }

        return placeAmount;
    }

    /**
     * 不满60分钟，按60分钟收费
     *
     * @param time
     * @return
     */
    private int getHourCeilTime(int time) {
        int diff = time % 3600;
        return diff >= 60 ? time + (3600 - diff) : time - diff;
    }

}
